#include "component.h"
#include "co_debug.h"
#include "menu.h"
#include "ble_rev_main.h"

#define ATE_MAIN_LOG(format, ...) __OSAL_LOG("[mc60_main.c:%d] " format "\r\n", __LINE__, ##__VA_ARGS__)
#define __ATE_MAIN_LOG(format, ...) __OSAL_LOG(format, ##__VA_ARGS__)

#define MC60_MAIN_LOG_HEX(note, array, len)   log_debug_array_ex(note, array, len)


#define TIME_DEC2BCD(t) OSAL_DEC2BCD(t[0]), \
                        OSAL_DEC2BCD(t[1]), \
                        OSAL_DEC2BCD(t[2]), \
                        OSAL_DEC2BCD(t[3]), \
                        OSAL_DEC2BCD(t[4]), \
                        OSAL_DEC2BCD(t[5])


#define  LED_COUNT  1//2
/* 产测模式接收消息命令 */
#define CMD_CHANGE_WORK_MODE 0x01        //门锁产测模式切换
#define CMD_SET_DOORLOCK_PARA 0x05       //设置门锁参数
#define CMD_READ_LOCK_VOLTAGE 0x10       //读取门锁电压
#define CMD_LOCKBODY_TEST 0x14           //锁体测试

#define CMD_NB_CSQ          0XA1   //读取CSQ

//BLE-->MCU 
#define CMD_BLE_UNLOCK  0x0100//0x0001       开锁
#define CMD_BLE_LOCKED  0x0200//0x0002       关锁
#define CMD_BLE_GET_LOCKSTATE 0x0300//0x0003 获取门锁开关状态
#define CMD_BLE_GET_BAT 0x0206//0x0602       获取电量

#define CMD_BLE_CONNECT_STASUS  0x0008//0x0800       通知蓝牙连接状态
#define CMD_BLE_IDENTIFICATION_RES  0x0801//响应启动身份识别指令
#define CMD_BLE_GET_ACCESS_CODE_STATUS 0x0107//0x0701       ACCESS code 激活状态通知 

#define CMD_BLE_ADD_SINGLE_NFC_STATUS 0x0306//     返回用户添加单个NFC卡片结果   swap 
#define CMD_BLE_DEL_SINGLE_NFC_STATUS 0x030a//     返回用户删除单个NFC卡片结果 
#define CMD_BLE_DEL_ALL_NFC_STATUS    0x030e//     返回用户删除全部 NFC 卡片结果
#define CMD_BLE_DEL_ID_NFC_STATUS     0x0310//     返回用户删除特定序号 NFC 卡片结果  
#define CMD_BLE_ADD_NFC_CANCEL_STATUS     0x0308//     返回用户取消添加 NFC 卡片结果
#define CMD_BLE_DEL_NFC_CANCEL_STATUS     0x030c//     返回用户取消删除 NFC 卡片结果
#define CMD_BLE_ACCESS_CODE_STATUS    0x0703//     ACCESS code 校验失败通知
#define CMD_BLE_NFC_VERIFICATION_STATUS    0x0312//     NFC 卡校验失败通知
#define CMD_BLE_GET_HOMEKIT_PAIR_STATUS    0xa00a//    回复用户按键触发 homekit 配对广播

//MCU-->BLE 
#define CMD_MCU_LOCKSTATE_CHANGE  0x0010//0x1000  门锁状态改变
#define CMD_MCU_RESET             0x0109//0x0901  通知蓝牙恢复出厂设置 
#define CMD_BLE_ACCESS_CODE_SEND  0x0702//ACCESS code 输入数字序列
#define CMD_BLE_ADD_SINGLE_NFC    0x0305//用户添加单个 NFC 卡片
#define CMD_BLE_ADD_SINGLE_NFC_CANCEL    0x0307//用户取消添加单个 NFC 卡片
#define CMD_BLE_DEL_SINGLE_NFC    0x0309//用户删除单个 NFC 卡片
#define CMD_BLE_DEL_SINGLE_NFC_CANCEL    0x030b//用户取消删除单个 NFC 卡片
#define CMD_BLE_DEL_ALL_NFC    0x030d//用户删除全部 NFC 卡片
#define CMD_BLE_DEL_ID_NFC    0x030f//用户删除特定序号 NFC 卡片的指令
#define CMD_BLE_SET_HOMEKIT_PAIR    0xa009//用户按键触发 homekit 配对广播


/* 产测模式上报消息命令 */
#define CMD_LOCK_STATUS_REPORT 0x20      //门锁休眠/上电/唤醒状态上报
#define CMD_READ_KEY_REPORT 0x21         //门锁上报按下键值

/*ACK回复的错误类型*/
#define CMD_EXECUTING 0x00  //命令正在执行，还需再次执行才能得到结果
#define CMD_EXE_ONCE 0x01   //命令执行完一次，还需要再次执行
#define CMD_EXE_OK 0x80     //命令执行成功
#define CMD_EXE_ERR 0x81    //命令执行失败
#define CMD_EXE_OK_END 0x82 //命令执行结束（当有多个应答包时，最后一个应答发0x82）

AppHandle_t app_handle = NULL;

static uint8_t access_code_err_flag = 0;

// static void ATE_test_process_cb(TimerHandle_stu_t handle);
static void ATE_LockMsgCb(void *msg, uint16_t len);
FlagStatus Menu_GetAppAddFlag(void);
uint8_t Menu_Exit_Managemode(void);
void Menu_SwitchMenu(MenuType_enum_t menu);
void Menu_PlayKeyNum(uint8_t keyType, uint8_t keyNum);
FlagStatus Menu_GetAppAddCardFlag(void);
void Menu_SetAppAddCardFlag(FlagStatus delflag);

/**
  * @brief  读门锁电压
  * @param  pAckDataBuf：应答数据域指针
  * @param  pAckDataLen：应答数据域长度
  * @retval 执行结果
  */
static uint8_t ATE_ReadLockVoltage(uint8_t *pData,uint8_t *pAckDataBuf, uint16_t *pAckDataLen)
{
    *pAckDataLen = 1;
    *pAckDataBuf = (uint8_t)SYS_CALL(Battery_Get);
    ATE_MAIN_LOG("ATE_ReadLockVoltage :%d \r\n", *pAckDataBuf);
    
    return CMD_EXE_OK;
}

/**
  * @brief  锁体测试
  * @param  pData：数据域指针
  * @param  pAckDataBuf：应答数据域指针
  * @param  pAckDataLen：应答数据域长度
  * @retval 执行结果
  */
static uint8_t ATE_LockBodyTest(uint8_t *pData, uint8_t *pAckDataBuf, uint16_t *pAckDataLen)
{
    uint8_t dataBuff[1] = {0};
    ATE_MAIN_LOG("ATE_LockBodyTest,%d", pData[0]);//ATE_LOG_D
    if (pData[0] == 0x00) //开锁
    {
        //test_type = UNLOCK_TEST;
        dataBuff[0] = LOCK_CTRL_UNLOCK;
        Lock_TestCtrl(LOCK_UNLOCK_TEST_MODE, dataBuff, 1);
    }
    else if (pData[0] == 0x01) //关锁
    {
        //test_type = LOCKED_TEST;
        dataBuff[0] = LOCK_CTRL_LOCKED;
        Lock_TestCtrl(LOCK_UNLOCK_TEST_MODE, dataBuff, 1);
    }
    else if(pData[0] == 0x02) //自学习
    {
        //test_type = MOTOR_TEST_MODE;
        dataBuff[0] = 0;
        Lock_TestCtrl(MOTOR_TEST_MODE, dataBuff, 0); 
    }
    else if(pData[0] == 0x03) //检测光耦挡片
    {
        //test_type = HALL_OC_TEST_MODE;
        dataBuff[0] = 0;
        Lock_TestCtrl(HALL_OC_TEST_MODE, dataBuff, 0); 
    }
    else if (pData[0] == 0x04) //停止
    {
        //test_type = LOCK_STOP_TEST;
        dataBuff[0] = LOCK_CTRL_STOP;
        Lock_TestCtrl(LOCK_UNLOCK_TEST_MODE, dataBuff, 1);
    }
    return CMD_EXECUTING;
}

/**
 * @brief 读取NB的CSQ回调
 *
 *
 * @note
 */
static void FuncAte_NB_CSQ_Handle(uint8_t NbRssi)
{
    // uint8_t ack_data[64] = {0};
    // uint8_t CSQ = 0;
    // uint8_t controlStatus = 0;

    // ATE_MAIN_LOG("FuncAte_NB_CSQ_Handle NbRssi:%d\r\n",NbRssi);
    
    // CSQ = NbRssi;
    // ack_data[0] = 0x80;
    // ack_data[1] = CSQ;
    // ExtKds_Send(CMD_NB_CSQ, ack_data, 2, NULL); 

    // controlStatus = NB_CONTROL_ENTER_PSM;
    // Nb_SendCmdToNb(&controlStatus, sizeof(controlStatus));
}

/**
  * @brief  读取NB的CSQ
  *
  * @return 命令执行结果
  */
static uint8_t ATE_ReadNB_CSQ(void)
{
    ATE_MAIN_LOG("ATE_ReadNB_CSQ\r\n");
   // SYS_CALL(NbMain_get_CSQ, FuncAte_NB_CSQ_Handle);

    return CMD_EXECUTING;
}

static void mc60_uart_send_callback(uint16_t cmd, void *data, uint16_t len)
{
}

/**
  * @brief  LOCK组件消息回调
  * @note   
  *
  * @param  msg 消息指针
  * @param  len 消息数据长度
  * @return void
  */
static void ATE_LockMsgCb(void *msg, uint16_t len)
{
        uint8_t dataBuff[4] = {0};
        uint8_t isKeyPressed = 0;
        uint16_t cmd_lock = 0x0010;
        uint16_t ack_len = 4;
        uint8_t ack_data_unlock[4] = {0x00, 0xFF, 0xFF, 0xFF};
        uint8_t ack_data_locked[4] = {0x01, 0xFF, 0xFF, 0xFF};
        LockMsg_t *lock = (LockMsg_t *)msg;

        ATE_MAIN_LOG("ATE_LockMsgCb, door_status:%d, lock_status:%d", lock->door, lock->lock);

        if (lock->lock == LOCK_ACTION_LOCKED || lock->lock == LOCK_ACTION_LOCKED_MACH) //上锁成功
        {
            ATE_MAIN_LOG("LOCKED<<<<<<<<<<<<<<\\n\n");//NULL
            Mc60_Send(cmd_lock, ack_data_locked, ack_len, mc60_uart_send_callback);
             
        }
       else if (lock->lock == LOCK_ACTION_UNLOCK_NO_BACK || lock->lock == LOCK_ACTION_UNLOCK || lock->lock == LOCK_ACTION_AUTO_DIR_CHECK_SUCCESS || lock->lock == LOCK_ACTION_UNLOCK_MACH) //开锁成功（开锁流程已结束，未回拖） 
       {
            ATE_MAIN_LOG("UNLOCK<<<<<<<<<<<<<<\\n\n");
           Mc60_Send(cmd_lock, ack_data_unlock, ack_len, mc60_uart_send_callback); 
       }     
}
//ACCESS
uint8_t get_access_code_err_flag(void)
{
    uint8_t ret = 0;

    ret = access_code_err_flag;
    return ret;
}

void set_access_code_err_flag(uint8_t flag)
{
    access_code_err_flag = flag;
}

static void Ate_ExtendKdsMsgCb(void *msg, uint16_t len)
{
    Mc60UartMsg_t *extend_kds = (Mc60UartMsg_t *)msg;
    uint8_t unlock[7] = {0xFF,0xFF,0xFF,0xFF,0x3C,0x8D,0x00};
	uint8_t lock_state = 0;
    uint8_t idenfify = 0;
    uint8_t card_id = 0;
    uint32_t card_id_save = 0;
    int16_t result = 0;//用于返回给app的添加卡片结果  0 - 成功 , 1 - 失败, 2 - 卡片已存在 3 - 录入超时
    static uint8_t inputKeysNumber;//暂存输入的卡片编号
	Ble_enroll_nfc_ack_stu_t Ble_enrollnfc_ack = {0};  

    ATE_MAIN_LOG("msgType:%d", extend_kds->msgType);
    MC60_MAIN_LOG_HEX("Ate_ExtendKdsMsgCb", extend_kds->data, extend_kds->len);
    if (extend_kds->msgType == MC60_RECV_CMD_PACKET)
    {
        uint16_t ack_len = 0;
        uint8_t *ack_data = NULL;

        if (msg == NULL || len == 0)
        {
            ATE_MAIN_LOG("msg is null\r\n");
            return;
        }

        ATE_MAIN_LOG("Ate receive cmd : %04X", extend_kds->cmd);  
        ATE_MAIN_LOG("Ate receive len : %d", extend_kds->len);
        //MC60_MAIN_LOG_HEX("Ate_ExtendKdsMsgCb", extend_kds->data, extend_kds->len);//20 16 12 4

        ack_data = OSAL_Malloc(256);
        if (ack_data != NULL)
        {
            memset(ack_data, 0x00, 256);
        }
        else
        {
            ATE_MAIN_LOG("OSAL_Malloc is null\r\n");
            return ;
        }

        
        
        switch (extend_kds->cmd)
        { 
            case CMD_BLE_UNLOCK: 
                    ack_len = 7;
                    if(extend_kds->data[8] == 0x22 || extend_kds->data[8] == 0x33 || extend_kds->data[8] == 0x44)
                    {
                        //Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                        Audio_Play(YAN_ZHENG_CHENG_GONG, RESET);//0x33 不播这句话?
                        if(extend_kds->data[8] == 0x33 )
                        {
                            set_access_code_err_flag(1);
                        }      
                    }            
                    memcpy(ack_data, unlock, ack_len);
                    // MC60_MAIN_LOG_HEX("ack_data", ack_data, ack_len);
                    Mc60_Send(extend_kds->cmd, ack_data, ack_len , mc60_uart_send_callback); //NULL
                    ATE_MAIN_LOG("CMD_BLE_UNLOCK %x\n",extend_kds->data[8]);
                    Local_LockControl(0xFF, 0xFF, LOCK_CTRL_UNLOCK);
            break;

             case CMD_BLE_LOCKED:        
                    ack_len = 7;
                    if(extend_kds->data[8] == 0x33)//访问码关锁指令
                    {
                        //Audio_Play(YAN_ZHENG_CHENG_GONG, RESET);
                        set_access_code_err_flag(1);
                    }      
                    memcpy(ack_data, unlock, ack_len);
                    Mc60_Send(extend_kds->cmd, ack_data, ack_len , mc60_uart_send_callback);
                    ATE_MAIN_LOG("CMD_BLE_LOCKED\n");
                    Local_LockControl(0xFF, 0xFF, LOCK_CTRL_LOCKED); 
            break; 
            
            case CMD_BLE_CONNECT_STASUS:        
                    ack_len = 1;                
                    if(extend_kds->data[0] == 1)
                    {
                        idenfify = 1;
                    }
                    else
                    {
                        if(extend_kds->data[0] == 3)
                        {
                            //3: 闪红灯 TODO: LED提示--暂定闪2秒
                           Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                        }
                        else if(extend_kds->data[0] == 4)
                        {
                            //4: 闪蓝灯 TODO: LED提示--暂定闪2秒
                            Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_BLUE, FINGER_LED_BLUE, LED_COUNT); // 成功： 闪蓝灯1次
                        }
                        if (ack_data != NULL)
                        {
                            OSAL_Free(ack_data);        
                        }
                        ATE_MAIN_LOG("CMD_BLE_CONNECT_STASUS return\n");
                        return ;                      
                    }
                    //1: 红蓝对闪  TODO: LED提示--暂定闪2秒--或者后面看下闪绿灯
                    Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次 
                    memcpy(ack_data, &idenfify, ack_len);
                    Mc60_Send(OSAL_SWAP16(CMD_BLE_IDENTIFICATION_RES);, ack_data, ack_len , mc60_uart_send_callback);
                    ATE_MAIN_LOG("CMD_BLE_CONNECT_STASUS OK\n");      
            break; 
            //
            case OSAL_SWAP16(CMD_BLE_ADD_SINGLE_NFC_STATUS):        
                        if(extend_kds->data[0] == 1)
                        {
                            card_id = extend_kds->data[1];
                            Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                            Audio_Play(TIAN_JIA_CHENG_GONG_BIAN_HAO, RESET);
                            void Set_Appaddkey_Res(FlagStatus Result);
                            Set_Appaddkey_Res(SET);
                    #if 1
                            inputKeysNumber = SYS_CALL(Users_GetValidId, USERS_TYPE_CARD); // TODO: 参考菜单处理
                            // if (inputKeysNumber == 0xFF)
                            // {
                            //     /* 没有空闲的存储，该类型密钥已满 */
                            //     // 切换菜单时会判断密钥是否满
                            //     //Audio_Play(audioNum, RESET);
                            //     //return Menu_GetFatherMenu(menuCurrent);
                            // }

                            //FUNC_BLE_LOG_HEX("pwd:", pwd, pwd_length);//003
                            // SUCCESS == SYS_CALL(Users_FindIdleKeyID, keyType, keyNum) 增加密码是否被占用的判断
                            card_id_save = card_id;
                            UsersAddRes_enum_t AddRes = SYS_CALL(Users_Add, USERS_TYPE_CARD, inputKeysNumber, &card_id_save, sizeof(card_id_save), USERS_ATTR_FOREVER, RESET);
                            ATE_MAIN_LOG("AddRes1:%d", AddRes);  
                            switch (AddRes) 
                            {
                                case ADD_SUCCESS:
                                    Local_LockSaveRecord(EVENT_TYPE_PROGRAM, USERS_TYPE_CARD, EVENT_CODE_ADD, inputKeysNumber);
                                    break;
                                
                                // case ADD_ERR_TOO_SIMPLE:
                                //     //keySetAck->errno = ERRNO_PWD_ILLEGAL;
                                //     break;
                                // case ADD_ERR_EXISTS:
                                //     //keySetAck->errno = ERRNO_PWD_REPETITION;
                                //     break;
                                // case ADD_ERR_RANGE:
                                //     //keySetAck->errno = ERRNO_PWD_ILLEGAL;
                                //     break;
                                case ADD_ERR_CARD_EXISTS:
                                    //keySetAck->errno = ERRNO_PWD_REPETITION;
                                    break;
                                case ADD_ERR_KEYS_LIB_IS_FULL:
                                    //keySetAck->errno = ERRNO_PWD_FULL;
                                    break;
                                default:
                                    //keySetAck->errno = ERRNO_UNKNOWN;
                                    break;
                            }
                    #endif 

                            //播放编号: 0--49 ---> 101-150
                            Menu_PlayKeyNum(USERS_TYPE_CARD, card_id); // 播放添加成功的语音
			                Device_DelayMs(20); // 单线语音在后板，播报时屏蔽中断，OS2OS接收中断异常，语音被插播
                            result = NFC_ENROLL_SUCCESS;
                        } //3: 卡重复错误
                        else if(extend_kds->data[0] == 3)
                        {
                            Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                            Audio_Play(TIAN_JIA_SHI_BAI, RESET);
                            Audio_Play(KIA_PIAN_YI_CUN_ZAI, RESET);
                            result = NFC_ENROLL_EXIST;
                        }
                        else 
                        {
                            Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                            Audio_Play(TIAN_JIA_SHI_BAI, RESET);
                            result = NFC_ENROLL_FAILED;
                        }
                        if (ack_data != NULL)
                        {
                            OSAL_Free(ack_data);        
                        }
                        //根据app 添加的标志做处理， 如果是app添加，则直接退出管理模式；否则就退出到添加用户设置菜单
                        if( Menu_GetAppAddFlag() == RESET)
                        {                       
                            Menu_SwitchMenu(MENU_ADDUSER_SET);
                        }
                        else
                        {
                            Ble_enrollnfc_ack.result = result; 
                            //TODO:使用实际的id 还是 密钥管理的编号
                            Ble_enrollnfc_ack.user_id = inputKeysNumber + 101;
                            SYS_CALL(Del_Nfcaddtimeout_timer);
                            SYS_CALL(FunBle_Enroll_Nfc_Notify, &Ble_enrollnfc_ack);  
                            //取消添加卡片，有添加卡片失败的声音提示 ？
                            //退出卡片添加                            
                            Menu_Exit_Managemode();
                        }          
                        ATE_MAIN_LOG("CMD_BLE_ADD_SINGLE_NFC_STATUS\n");
                        return ;                      
            break; 

            case OSAL_SWAP16(CMD_BLE_DEL_SINGLE_NFC_STATUS):        
                    if(extend_kds->data[0] == 1)
                    {
                        Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                        Audio_Play(SHAN_CHU_CHENG_GONG, RESET);
                    }
                    else 
                    {
                        Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                        Audio_Play(SHAN_CHU_SHI_BAI, RESET);
                    }
                    if (ack_data != NULL)
                    {
                        OSAL_Free(ack_data);        
                    }
                    ATE_MAIN_LOG("CMD_BLE_DEL_SINGLE_NFC_STATUS\n");
                    return ;                      
            break; 

            case OSAL_SWAP16(CMD_BLE_DEL_ALL_NFC_STATUS):        
                    if(extend_kds->data[0] == 1)
                    {
                        Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                        //Audio_Play(SHAN_CHU_CHENG_GONG, RESET);
                    }
                    else 
                    {
                        Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                        //Audio_Play(SHAN_CHU_SHI_BAI, RESET);
                    }
                    if (ack_data != NULL)
                    {
                        OSAL_Free(ack_data);        
                    }
                    ATE_MAIN_LOG("CMD_BLE_DEL_ALL_NFC_STATUS\n");
                    return ;                      
            break; 

            ///
             case OSAL_SWAP16(CMD_BLE_DEL_ID_NFC_STATUS):        
                    if(extend_kds->data[0] == 1)
                    {
                        if(Menu_GetAppAddCardFlag() == RESET)
                        {
                            Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                            Audio_Play(SHAN_CHU_CHENG_GONG, RESET);
                        }
                        else
                        {
                            Menu_SetAppAddCardFlag(RESET);
                        }
                    }
                    else 
                    {
                        if(Menu_GetAppAddCardFlag() == RESET)
                        {                 
                            Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                            Audio_Play(SHAN_CHU_SHI_BAI, RESET);
                        }
                        else
                        {
                            Menu_SetAppAddCardFlag(RESET);
                        }
                    }
                    if (ack_data != NULL)
                    {
                        OSAL_Free(ack_data);        
                    }
                    ATE_MAIN_LOG("CMD_BLE_DEL_ID_NFC_STATUS\n");
                    return ;                      
            break; 
            //
            case OSAL_SWAP16(CMD_BLE_ADD_NFC_CANCEL_STATUS):        
                    if(extend_kds->data[0] == 1)
                    {
                       //Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                       // Audio_Play(SHAN_CHU_CHENG_GONG, RESET);///
                       ATE_MAIN_LOG("ADD_NFC_CANCEL OK");
                    }
                    else 
                    {
                     // Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                     //   Audio_Play(SHAN_CHU_SHI_BAI, RESET);
                     ATE_MAIN_LOG("ADD_NFC_CANCEL FAILED");
                    }
                    if (ack_data != NULL)
                    {
                        OSAL_Free(ack_data);        
                    }
                    ATE_MAIN_LOG("CMD_BLE_ADD_NFC_CANCEL_STATUS\n");
                    return ;                      
            break; 
            
            case OSAL_SWAP16(CMD_BLE_DEL_NFC_CANCEL_STATUS):        
                    if(extend_kds->data[0] == 1)
                    {
                        //Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                        //Audio_Play(SHAN_CHU_CHENG_GONG, RESET);
                        ATE_MAIN_LOG("DEL_NFC_CANCEL OK");
                    }
                    else 
                    {
                        //Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                        //Audio_Play(SHAN_CHU_SHI_BAI, RESET);
                        ATE_MAIN_LOG("DEL_NFC_CANCEL FAILED");
                    }
                    if (ack_data != NULL)
                    {
                        OSAL_Free(ack_data);        
                    }
                    ATE_MAIN_LOG("CMD_BLE_DEL_NFC_CANCEL_STATUS\n");
                    return ;                      
            break; 

            case OSAL_SWAP16(CMD_BLE_ACCESS_CODE_STATUS):        
                    // if(extend_kds->data[0] == 1)
                    // {
                    //     Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                    //     //验证成功
                    //     Audio_Play(YAN_ZHENG_CHENG_GONG, RESET);
                    // }
                    // else 
                    if(extend_kds->data[0] == 0)
                    {
                        Menu_ProcessVerifyFailed(); 
                        Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                        set_access_code_err_flag(1);
                    }
                    if (ack_data != NULL)
                    {
                        OSAL_Free(ack_data);        
                    }
                    ATE_MAIN_LOG("CMD_BLE_ACCESS_CODE_STATUS\n");
                    return ;                      
            break; 

            case OSAL_SWAP16(CMD_BLE_NFC_VERIFICATION_STATUS):        
                    //if(extend_kds->data[0] == 1)
                    //{
                        //Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                        //验证成功 
                        //Audio_Play(YAN_ZHENG_CHENG_GONG, RESET);
                    //}
                    //else
                    if(extend_kds->data[0] == 0) 
                    {
                        Menu_ProcessVerifyFailed(); 
                        Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                      
                    }
                    if (ack_data != NULL)
                    {
                        OSAL_Free(ack_data);        
                    }
                    ATE_MAIN_LOG("CMD_BLE_NFC_VERIFICATION_STATUS\n");
                    return ;                      
            break; 

            case OSAL_SWAP16(CMD_BLE_GET_HOMEKIT_PAIR_STATUS):        
                    if(extend_kds->data[0] == 1)
                    {
                        Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_GREEN, FINGER_LED_GREEN, LED_COUNT); // 成功： 闪绿灯1次
                    }
                    else 
                    {
                        Finger_LedControl(FINGER_FLASHING_LED_MODE, FINGER_LED_RED, FINGER_LED_RED, LED_COUNT); // 失败： 闪红灯1次
                    }
                    if (ack_data != NULL)
                    {
                        OSAL_Free(ack_data);        
                    }
                    ATE_MAIN_LOG("CMD_BLE_GET_HOMEKIT_PAIR_STATUS\n");
                    return ;                      
            break; 

            case CMD_BLE_GET_LOCKSTATE:     
                    ack_len = 1;
                    //获取门锁状态
                    lock_state = SYS_CALL(local_LockGetLockStatus);
                    ATE_MAIN_LOG("lock_state:%d\n", lock_state);
                    if (lock_state == LOCK_ACTION_LOCKED || lock_state == LOCK_ACTION_LOCKED_MACH) //上锁成功
                    {
                        lock_state = 1;
                    }
                    else if (lock_state == LOCK_ACTION_UNLOCK_NO_BACK || lock_state == LOCK_ACTION_UNLOCK || lock_state == LOCK_ACTION_UNLOCK_MACH) //开锁成功
                    {
                        lock_state = 0;
                    }
                    else
                    {
                        lock_state = 2;
                    }
                    ack_data[0] = lock_state;
                    Mc60_Send(extend_kds->cmd, ack_data, ack_len , NULL);
                    ATE_MAIN_LOG("MC60_MAIN CMD_BLE_GET_LOCKSTATE\n");  
            break;

            case CMD_BLE_GET_BAT:        
                    ack_len = 2;
                    //获取电量，并转换成百分比
                    uint8_t bat = SYS_CALL(Battery_Get);
                
                    ack_data[0] = 0xFF;
                    ack_data[1] = bat;

                    Mc60_Send(extend_kds->cmd, ack_data, ack_len , NULL);
                    ATE_MAIN_LOG("MC60_MAIN CMD_BLE_GET_BAT\n");              
            break;
                  
            case CMD_BLE_GET_ACCESS_CODE_STATUS:        
                    if(extend_kds->data[0] == 0)
                    {
                         //未激活--则本地的错误密码不用发给MC60 
                    }
                    else if(extend_kds->data[0] == 1)
                    {
                        //
                        //已激活 
                    }                                  
                    ATE_MAIN_LOG("MC60_MAIN CMD_BLE_GET_ACCESS_CODE_STATUS\n");      
            break;

        case CMD_READ_LOCK_VOLTAGE:
//            if(extend_kds->len == 1)
//            {
//               newBatTestFlag =1;
//            }
//            else
//            {
//                newBatTestFlag =0;
//            }
            ack_data[0] = ATE_ReadLockVoltage(extend_kds->data,&ack_data[1], &ack_len); //! 读取门锁电压
            break;
       
        case CMD_LOCKBODY_TEST: //! 锁体测试
            ack_data[0] = ATE_LockBodyTest(extend_kds->data, &ack_data[1], &ack_len);
            break;

        case CMD_NB_CSQ:  
            ack_data[0] = ATE_ReadNB_CSQ();
            break;

        default:
            ack_data[0] = CMD_EXECUTING;
            break;
        }

        ATE_MAIN_LOG("ack ret :%02X",ack_data[0]);
        if (ack_data[0] != CMD_EXECUTING)
        {
            //Mc60_Send(extend_kds->cmd, ack_data, ack_len + 1, NULL); //发送ACK   ExtKds_Send
          //  Mc60_Send(extend_kds->cmd, ack_data, ack_len , NULL);
        }

        if (ack_data != NULL)
        {
            OSAL_Free(ack_data);
        }

    }
    else if (extend_kds->msgType == MC60_EXEC_CB)
    {
        if (extend_kds->cmd == 0xB0)//过滤入网指令
        {
            return;
        }
        ATE_MAIN_LOG("cb: %x, cmd: %02x, len: %02x\r\n", extend_kds->cb, extend_kds->cmd, extend_kds->len);
        if (extend_kds->cb)
        {
            extend_kds->cb(extend_kds->cmd, extend_kds->data, extend_kds->len);
        }
    }
}

static void MC60_Send_Reset_Cmd(void)
{
    uint16_t cmd = CMD_MCU_RESET;
    uint16_t ack_len = 1;
    uint8_t ack_data = 0xab;

    ATE_MAIN_LOG("MC60_Send_Reset_Cmd\r\n");
    Mc60_Send(cmd, &ack_data, ack_len, mc60_uart_send_callback); 
}

static void MC60_Send_Access_Code(uint8_t *pData, uint8_t len)
{
    uint16_t cmd = OSAL_SWAP16(CMD_BLE_ACCESS_CODE_SEND);
    uint16_t ack_len = len + 1;
    uint8_t ack_data[9] = {len, 0, 0, 0, 0, 0, 0, 0, 0};
    memcpy(&ack_data[1], pData, len); 
    MC60_MAIN_LOG_HEX("ack_data", ack_data, ack_len);

    ATE_MAIN_LOG("MC60_Send_Access_Code\r\n");
    Mc60_Send(cmd, &ack_data, ack_len, mc60_uart_send_callback); 
}

static void MC60_Add_Single_Nfc(void)
{
    uint16_t cmd = OSAL_SWAP16(CMD_BLE_ADD_SINGLE_NFC);
    uint16_t ack_len = 1;
    uint8_t ack_data = 0x01;

    ATE_MAIN_LOG("MC60_Add_Single_Nfc\r\n");
    Mc60_Send(cmd, &ack_data, ack_len, mc60_uart_send_callback); 
}

static void MC60_Add_Single_Nfc_Cancel(void)
{
    uint16_t cmd = OSAL_SWAP16(CMD_BLE_ADD_SINGLE_NFC_CANCEL);
    uint16_t ack_len = 1;
    uint8_t ack_data = 0x01;

    ATE_MAIN_LOG("MC60_Add_Single_Nfc_Cancel\r\n");
    Mc60_Send(cmd, &ack_data, ack_len, mc60_uart_send_callback); 
}

static void MC60_Del_Single_Nfc(void)
{
    uint16_t cmd = OSAL_SWAP16(CMD_BLE_DEL_SINGLE_NFC);
    uint16_t ack_len = 1;
    uint8_t ack_data = 0x01;

    ATE_MAIN_LOG("MC60_Del_Single_Nfc\r\n");
    Mc60_Send(cmd, &ack_data, ack_len, mc60_uart_send_callback); 
}

static void MC60_Del_Single_Nfc_Cancel(void)
{
    uint16_t cmd = OSAL_SWAP16(CMD_BLE_DEL_SINGLE_NFC_CANCEL);
    uint16_t ack_len = 1;
    uint8_t ack_data = 0x01;

    ATE_MAIN_LOG("MC60_Del_Single_Nfc_Cancel\r\n");
    Mc60_Send(cmd, &ack_data, ack_len, mc60_uart_send_callback); 
}

static void MC60_Del_All_Nfc(void)
{
    uint16_t cmd = OSAL_SWAP16(CMD_BLE_DEL_ALL_NFC);
    uint16_t ack_len = 1;
    uint8_t ack_data = 0x01;

    ATE_MAIN_LOG("MC60_Del_All_Nfc\r\n");
    Mc60_Send(cmd, &ack_data, ack_len, mc60_uart_send_callback); 
}

static void MC60_Send_Del_Id_Nfc(uint8_t nfcid)
{
    uint16_t cmd = OSAL_SWAP16(CMD_BLE_DEL_ID_NFC);
    uint16_t ack_len =  1;
    uint8_t ack_data = nfcid;
//    MC60_MAIN_LOG_HEX("ack_data", ack_data, ack_len);
	 ATE_MAIN_LOG("nfcid:%d\r\n", nfcid);
	
    ATE_MAIN_LOG("MC60_Send_Del_Id_Nfc\r\n");
    Mc60_Send(cmd, &ack_data, ack_len, mc60_uart_send_callback); 
}

static void MC60_Send_Homekit_Pair(void)
{
    uint16_t cmd = OSAL_SWAP16(CMD_BLE_SET_HOMEKIT_PAIR);
    uint16_t ack_len =  2;
    uint8_t ack_data[2] = {0xb3, 0x63};
    MC60_MAIN_LOG_HEX("ack_data", ack_data, ack_len);

    ATE_MAIN_LOG("MC60_Send_Homekit_Pair\r\n");
    Mc60_Send(cmd, &ack_data, ack_len, mc60_uart_send_callback); 
}


static ErrorStatus MC60_SleepCb(void)
{
    ATE_MAIN_LOG("Ate_main sleep_cb\r\n");
    return SUCCESS;
}

static void MC60_main(uint32_t wake_id, uint32_t wake_param)
{
    ATE_MAIN_LOG("MC60_main, wake_id:%ld, wake_param:%ld\r\n", wake_id, wake_param);
    app_handle = OSAL_AppCreate("APP_ATE", MC60_SleepCb); //
    OSAL_MessageSubscribe(app_handle, COMP_MC60_UART, Ate_ExtendKdsMsgCb);
    OSAL_MessageSubscribe(app_handle, COMP_LOCK, ATE_LockMsgCb);
    SYS_API(MC60_Send_Reset_Cmd);
    SYS_API(MC60_Send_Access_Code);
    SYS_API(MC60_Add_Single_Nfc);
    SYS_API(MC60_Add_Single_Nfc_Cancel);
    SYS_API(MC60_Del_Single_Nfc);
    SYS_API(MC60_Del_Single_Nfc_Cancel);
    SYS_API(MC60_Del_All_Nfc); 
    SYS_API(MC60_Send_Del_Id_Nfc); 
    SYS_API(MC60_Send_Homekit_Pair); 
}
APP_INIT_EXPORT(MC60_main);